<script lang="ts" setup>
  import { ref, computed, watch } from 'vue';
  import { Tabs, TabPane, Card, Space } from '@arco-design/web-vue';
  import { ApiManageList } from '/@/components/ApiManageList';
  import {
    queryArticlePage,
    queryPublishedArticlePage,
    queryPublishedButRejectedArticlePage,
    queryDraftPage,
    rejectArticle,
    deleteArticle,
    resolveArticle,
  } from '/@/api/article';
  import type { ArticleRecord } from '/@/api/model/articleModel';
  import { useRouter } from 'vue-router';
  import { PageEnum } from '/@/enums/pageEnum';
  import { Message, Modal } from '@arco-design/web-vue';

  const router = useRouter();

  // 标签页
  const activeKey = ref('');
  const TabsMap = {
    Essays: { title: '文章', key: PageEnum.CREATOR_CONTENT_ARTICLE_ESSAYS },
    Drafts: { title: '草稿箱', key: PageEnum.CREATOR_CONTENT_ARTICLE_DRAFTS },
  };
  watch(
    router.currentRoute,
    ({ path }) => {
      activeKey.value = path;
    },
    { immediate: true },
  );
  watch(activeKey, (key) => {
    if (key !== router.currentRoute.value.path) {
      router.push(key);
    }
  });

  // 文章状态
  const statusKey = ref('');
  const statusTabs = computed(() => {
    return [
      { title: '全部', key: 'all', api: queryArticlePage },
      { title: '已发布', key: 'published', api: queryPublishedArticlePage },
      { title: '已下架', key: 'rejected', api: queryPublishedButRejectedArticlePage },
    ];
  });
  const queryStatus = computed(() => {
    const { status } = router.currentRoute.value.query;
    return Array.isArray(status) ? status[0] : status;
  });
  watch(
    router.currentRoute,
    () => {
      if (router.currentRoute.value.path !== PageEnum.CREATOR_CONTENT_ARTICLE_ESSAYS) return;
      if (queryStatus.value && ['all', 'published', 'rejected'].includes(queryStatus.value)) {
        statusKey.value = queryStatus.value;
      } else {
        router.push({ query: { status: 'all' } });
      }
    },
    { immediate: true },
  );
  watch(statusKey, (status) => {
    if (router.currentRoute.value.path !== PageEnum.CREATOR_CONTENT_ARTICLE_ESSAYS) return;
    if (status !== queryStatus.value) {
      router.push({ query: { status } });
    }
  });
  const toEdit = ({ item }: { item: ArticleRecord }) => {
    window.open(`/editor/drafts/${item.id}`, '_blank');
  };
  const onDelete = ({ item, reload }: { item: ArticleRecord; reload: PromiseFn }) => {
    Modal.warning({
      title: '删除内容',
      content: '删除内容后不可恢复，确定删除吗？',
      onOk: async () => {
        try {
          await deleteArticle(item.id);
          Message.success('删除成功');
          reload();
        } catch (err) {
          Message.error((err as Error).message || '删除失败');
        }
      },
    });
  };

  const onReject = ({ item, reload }: { item: ArticleRecord; reload: PromiseFn }) => {
    Modal.warning({
      title: '下架文章',
      content: '确定下架吗？',
      onOk: async () => {
        try {
          await rejectArticle(item.id);
          Message.success('下架成功');
          reload();
        } catch (err) {
          Message.error((err as Error).message || '下架失败');
        }
      },
    });
  };

  const onResolve = async ({ item, reload }: { item: ArticleRecord; reload: PromiseFn }) => {
    try {
      await resolveArticle(item.id);
      Message.success('上架成功');
      reload();
    } catch (err) {
      Message.error((err as Error).message || '上架失败');
    }
  };

  const callActions = (item: ArticleRecord) => {
    const actions = [
      { label: '编辑', onClick: toEdit },
      { label: '删除', onClick: onDelete },
    ];
    if (item.state === 1) {
      actions.push({ label: '上架', onClick: onResolve });
    }
    if (item.state === 0) {
      actions.push({ label: '下架', onClick: onReject });
    }
    return actions;
  };
</script>

<template>
  <Card>
    <Tabs class="mb-[14px]" hoverable v-model:activeKey="activeKey" lazyLoad destroyOnHide>
      <TabPane :title="TabsMap.Essays.title" :key="TabsMap.Essays.key">
        <Tabs lazyLoad v-model:activeKey="statusKey" type="text" destroyOnHide>
          <TabPane v-for="item in statusTabs" :key="item.key" :title="item.title">
            <ApiManageList
              :api="item.api"
              :params="{ status: item.key }"
              :getLink="(item) => `/post/${item.id}`"
              :actions="callActions"
            >
              <template #desc="{ data }">
                <Space :size="[24, 0]" class="text-gray-500">
                  <template #split>|</template>
                  <span>{{ data.updateTime }}</span>
                  <Space :size="[12, 0]">
                    <template #split>·</template>
                    <span>{{ data.view }}展现</span>
                    <span>{{ data.read }}阅读</span>
                    <span>{{ data.like }}赞</span>
                    <span>{{ data.replay }}评论</span>
                    <span>{{ data.collect }}收藏</span>
                  </Space>
                </Space>
              </template>
            </ApiManageList>
          </TabPane>
        </Tabs>
      </TabPane>
      <TabPane :title="TabsMap.Drafts.title" :key="TabsMap.Drafts.key">
        <ApiManageList
          :api="queryDraftPage"
          :getLink="(item) => `/editor/drafts/${item.id}`"
          :actions="[
            { label: '编辑', onClick: (item) => toEdit(item) },
            { label: '删除', onClick: (item) => onDelete(item) },
          ]"
      /></TabPane>
    </Tabs>
  </Card>
</template>
